﻿using IM.Easy.Core.Extensions;
using IM.Easy.Core.Services;
using IM.Easy.Core.Utils;
using IM.Easy.Entity.Gen;
using IM.Easy.Entity.Log;
using IM.Easy.GenServices.Dtos;
using IM.Easy.GenServices.IServices;
using IM.Easy.Infrastructure.Query;
using Mapster;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IM.Easy.GenServices.Services
{
    public class GenTableService(ISqlSugarClient db) : AppServices(db), IGenTableService
    {
        /// <summary>
        /// 获取需要生成的信息
        /// </summary>
        /// <returns></returns>
        public GenTableDto GetGenInfo(Guid id)
        {
            var table = Db.Queryable<GenTable>()
                   .Includes(s => s.Columns.OrderBy(s => s.Order).ToList())
                   .Includes(s => s.Options)
                   .InSingle(id);
            return table.Adapt<GenTableDto>();
        }

        /// <summary>
        /// 更新生成信息
        /// </summary>
        public bool UpdateGenInfo(GenTable genTable)
        {
            var result = Db.UpdateNav(genTable)
                .Include(s => s.Options)
                .Include(s => s.Columns)
                .ExecuteCommand();
            return result;
        }

        public GenTable InsertGenTable(GenTable genTable)
        {
            if (!EnableImport(genTable.Name)) ExceptionUtils.ThrowBusinessException($"表已存在{genTable.Name}");
            genTable = Db.InsertNav(genTable).Include(s => s.Columns).Include(s => s.Options).ExecuteReturnEntity();
            return genTable;
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <returns></returns>
        public PageResponse<GenTableDto> GetList(GenTableQueryDto query)
        {
            var list = Db.Queryable<GenTable>();
            var exp = Expressionable.Create<GenTable>();
            exp = exp.AndIF(!string.IsNullOrEmpty(query.Name), s => s.Name.Contains(query.Name))
                     .AndIF(!string.IsNullOrEmpty(query.Desc), s => s.Desc.Contains(query.Desc))
                     .AndIF(query.BeginTime.HasValue, s => s.CreatedAt >= query.BeginTime)
                    .AndIF(query.EndTime.HasValue, s => s.CreatedAt <= query.EndTime);
            var page = list
                .Where(exp.ToExpression())
                .ToPageListAsync<GenTable, GenTableDto>(query);
            return page;
        }

        /// <summary>
        /// 获取数据库列表
        /// </summary>
        /// <returns></returns>
        public PageResponse<DbTableDto> GetDbTableList(DbTableQueryDto query)
        {
            var page = new PageResponse<DbTableDto>()
            {
                PageIndex = query.PageIndex,
                PageSize = query.PageSize,
            };
            var t = Db.DbMaintenance.GetTableInfoList(false);
            var list = t.Adapt<List<DbTableDto>>();
            //去除已导入了的
            var hasImported = Db.Queryable<GenTable>().ToList();
            list = list.Where(item => !hasImported.Any(imported => imported.Name == item.Name)).ToList();
            page.TotalNum = list.Count;
            list = list.WhereIF(!string.IsNullOrEmpty(query.Name), s => s.Name.Contains(query.Name, StringComparison.OrdinalIgnoreCase))
               .Skip(query.PageSize * (query.PageIndex - 1)).Take(query.PageSize)
               .OrderBy(f => f.Name)
               .ToList();
            page.Result = list;
            return page;
        }

        /// <summary>
        /// 获取数据库表信息
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public DbTableDto GetDbTable(string name)
        {
            var t = Db.DbMaintenance
                .GetTableInfoList(false)
                .FirstOrDefault(s => s.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
            if (t == null) ExceptionUtils.ThrowSystemException($"未找到表{name}");
            //获取列信息
            var columns = Db.DbMaintenance.GetColumnInfosByTableName(t.Name);
            var table = t.Adapt<DbTableDto>();
            table.Columns = columns;
            return table;
        }

        /// <summary>
        /// 判断是否能够进行导入
        /// </summary>
        /// <param name="name"></param>
        private bool EnableImport(string name)
        {
            var duplicate = Db.Queryable<GenTable>().Any(s => s.Name == name);
            return !duplicate;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <returns></returns>
        public bool Delete(Guid id)
        {
            var result = Db.DeleteNav<GenTable>(s => s.Id == id)
                        .IncludesAllFirstLayer()
                        .ExecuteCommand();
            return result;
        }
    }
}
